package com.fch.sdlibrary.ui.home;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProviders;

import com.fch.sdlibrary.BookActivity;
import com.fch.sdlibrary.R;
import com.fch.sdlibrary.entity.BaseResponse;
import com.fch.sdlibrary.entity.Book;
import com.fch.sdlibrary.global.MyGlobal;
import com.fch.sdlibrary.util.BookAdapter;
import com.fch.sdlibrary.util.PageInfo;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class HomeFragment extends Fragment {

    private HomeViewModel homeViewModel;
    private ListView listView;
    private List<Book> mData = new ArrayList<>();
    private Gson gson = new Gson();
    private BaseResponse baseResponse;
    private PageInfo pageInfo = new PageInfo();
    private BookAdapter adapter;
    private Integer pageNum = 0;

    public View onCreateView(@NonNull final LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        homeViewModel = ViewModelProviders.of(this).get(HomeViewModel.class);
        final View root = inflater.inflate(R.layout.fragment_home, container, false);
        listView = root.findViewById(R.id.my_list);

        adapter = new BookAdapter(mData, inflater);
        listView.setAdapter(adapter);
        send();

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Book book = (Book) listView.getAdapter().getItem(i);
                Intent intent = new Intent(root.getContext(), BookActivity.class);
                intent.putExtra("id", book.getBookId().toString());
                startActivity(intent);
            }
        });
        listView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {
                if (i == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    // 判断是否滚动到底部
                    if (absListView.getLastVisiblePosition() == absListView.getCount() - 1) {
                        //加载更多功能的代码
                        send();
                    }
                }
            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {

            }
        });

        return root;
    }


    private void send() {
        pageNum++;
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(3, TimeUnit.SECONDS)
                .build();//创建Http客户端
        Request request = new Request.Builder()
                .url(MyGlobal.PATH + "QueryAllBookByPage?pageNum=" + pageNum)//***.***.**.***为本机IP，xxxx为端口，/  /  为访问的接口后缀
                .get()
                .build();//创建Http请求
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //请求失败的处理
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // 更新UI的操作
                        Toast.makeText(getContext(), "链接失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //请求成功返回结果
                //如果希望返回的是字符串
                final String responseData = response.body().string();
                baseResponse = new BaseResponse<PageInfo>();
                Type type = new TypeToken<BaseResponse<PageInfo>>() {
                }.getType();
                baseResponse = gson.fromJson(responseData, type);
                pageInfo = (PageInfo) baseResponse.getData();
                if (pageInfo.getList().isEmpty())
                    return;
                mData.addAll(pageInfo.getList());
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // 更新UI的操作
                        Toast.makeText(getContext(), "新发现" + pageInfo.getList().size() + "条信息", Toast.LENGTH_SHORT).show();
                        adapter.notifyDataSetChanged();
                    }
                });
            }
        });
    }

//    private void send(final LayoutInflater inflater, final Integer pageNum) {
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                OkHttpClient client = new OkHttpClient();//创建Http客户端
//                Request request = new Request.Builder()
//                        .url(MyGlobal.PATH + "QueryAllBookByPage?pageNum=" + pageNum)//***.***.**.***为本机IP，xxxx为端口，/  /  为访问的接口后缀
//                        .get()
//                        .build();//创建Http请求
//                try {
//                    Response response = client.newCall(request).execute();//执行发送的指令
//                    final String responseData = response.body().string();//获取返回的结果
//                    System.out.println(responseData);
//                    baseResponse = new BaseResponse<PageInfo>();
//                    Type type = new TypeToken<BaseResponse<PageInfo>>() {
//                    }.getType();
//                    baseResponse = gson.fromJson(responseData, type);
//                    pageInfo = (PageInfo) baseResponse.getData();
//                    mData = pageInfo.getList();
//                    System.out.println(mData);
//                    //将布局添加到ListView中
//                    adapter = new BookAdapter(mData, inflater);
//                    getActivity().runOnUiThread(runnable);
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//
//        }).start();
//    }

}